﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace DFGK_WMS.Repository
{
    public class TTransferBinOrderRepository : BaseRepository<TTransferBinOrder>, ITTransferBinOrderRepository
    {
        public TTransferBinOrderRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        { 
        }

        /// <summary>
        /// 提交数据 （增加/修改/删除）
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool SubmitTransferBinOrderData(TTransferBinOrderDTO m)
        {
            //使用事务的原子性
            using (var trans = Context.Database.BeginTransaction())
            {
                try
                {
                    TTransferBinOrder tran = new TTransferBinOrder();
                    tran = Mapper.Map<TTransferBinOrder>(m);
                    bool isAdd = m.Id <= 0;
                    #region 添加移库单
                    if (isAdd)
                    {
                        tran.CreateUserId = m.SubmitUserId;
                        tran.CreateUserName = m.SubmitUserName;
                        tran.CreateDate = DateTime.Now;
                        tran.ModifyDate = DateTime.Now;
                        tran.ModifyUserId = m.ModifyUserId;
                        tran.ModifyUserName = m.ModifyUserName;
                        tran.CompanyName = "";//com.Name==null ? null : com.Name;
                        tran.Status = 0;
                    
                        Context.TTransferBinOrders.Add(tran);
                        Context.SaveChanges();
                        if (m.OrderDetailList != null && m.OrderDetailList.Count > 0)
                        {
                            foreach (var item in m.OrderDetailList)
                            {
                                item.OrderId = tran.Id;
                                item.OrderSn = tran.OrderSn;
                                item.CreateUserId = tran.CreateUserId;
                                item.CreateUserName = tran.CreateUserName;
                                item.CreateDate = tran.CreateDate;
                                item.ModifyUserId = tran.ModifyUserId;
                                item.ModifyUserName = tran.ModifyUserName;
                                item.ModifyDate = tran.ModifyDate;

                                #region 添加移库单明细
                                Context.TTransferBinOrderDetails.Add(item);
                                Context.SaveChanges();
                                #endregion
                            }
                        }
                    }
                    #endregion

                    #region 修改/删除 移库单和移库单明细
                    else
                    {
                        #region 修改移库单
                        tran.ModifyDate = DateTime.Now;
                        tran.ModifyUserId = m.ModifyUserId;
                        tran.ModifyUserName = m.ModifyUserName;
                        tran.CompanyName = "";//com.Name == null ? null : com.Name;
                        Context.TTransferBinOrders.Update(tran);
                        Context.SaveChanges();
                        #endregion

                        var listDetail = Context.TTransferBinOrderDetails.Where(t => t.OrderId == tran.Id).ToList();
                        if (listDetail != null && listDetail.Count > 0)
                        {
                            foreach (var item in listDetail)
                            {
                                Context.TTransferBinOrderDetails.Remove(item);
                            }
                            foreach (var item in m.OrderDetailList)
                            {
                                item.OrderId = tran.Id;
                                item.OrderSn = tran.OrderSn;
                                item.CreateUserId = tran.CreateUserId;
                                item.CreateUserName = tran.CreateUserName;
                                item.CreateDate = tran.CreateDate;
                                item.ModifyUserId = tran.ModifyUserId;
                                item.ModifyUserName = tran.ModifyUserName;
                                item.ModifyDate = tran.ModifyDate;

                                Context.TTransferBinOrderDetails.Add(item);
                                Context.SaveChanges();
                            }
                        }
                    }
                    #endregion
                    Context.SaveChanges();
                    //提交事务
                    trans.Commit();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    trans.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 删除移库单
        /// </summary>
        /// <param name="tid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelTransferBinOrder(int tid)
        {
            var mobj = Context.TTransferBinOrders.Find(tid);
            if (mobj != null)
            {
                Context.TTransferBinOrders.Remove(mobj);
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 获取可用仓位
        /// </summary>
        /// <param name="fromLocationId"></param>
        /// <param name="isPriorityFilling"></param>
        /// <param name="filterType"></param>
        /// <param name="toLogicalPartCode"></param>
        /// <returns></returns>
        public List<TCell> GetEnabledCellListByFromLocationId(string? toLogicalPartCode,int FromLocationId, bool isPriorityFilling = false, int filterType = 1)
        {
            var cellQuery = Context.TCells.AsNoTracking().ToList();
            var shelfQuery = Context.TShelves;
            var inventoryQuery = Context.TInventories;
            var inventory = inventoryQuery.Where(i => i.LocationId == FromLocationId).FirstOrDefault();

            if (inventory is null)
            {
                return null;
            }
            if (inventory.IsMultPallet == true)
            {
                toLogicalPartCode = "MultPallet";//花盘定死
            }
            List<int?> list=null;
            if(isPriorityFilling)
            {
                if (filterType == 1)
                {
                    list = inventoryQuery.Where(i => i.MaterialId == inventory.MaterialId && i.Status == 1).Select(i => i.LocationId).ToList();
                }
                else if (filterType == 2)
                {
                    list = inventoryQuery.Where(i => i.MaterialId == inventory.MaterialId && i.Status == 1).Select(i => i.LocationId).ToList();
                }
                else
                {
                    list = inventoryQuery.Where(i => i.Status == 1).Select(i => i.LocationId).ToList();
                }
                cellQuery = cellQuery.Where(c => list.Contains(c.Id) && c.Status == (int)EmCellStatus.Normal && c.IsLock == false && c.BusinessType == 0 && c.FullStatus == 0 && c.HeightType >= inventory.RealHeightType && c.LayerNo == inventory.LocationLayerNo && c.LineNo == inventory.LocationLineNo && c.ColumnNo > inventory.LocationColumnNo && c.DepthIndex == inventory.LocationDepth).ToList();
            }
            else
            {
                cellQuery = cellQuery.Where(c => c.Status == (int)EmCellStatus.Normal && c.FullStatus == 0 && c.IsLock == false && c.BusinessType == 0 && c.HeightType >= inventory.RealHeightType).ToList();
            }
            if (!string.IsNullOrEmpty(toLogicalPartCode))
            {
                cellQuery = cellQuery.Where(t => t.LogicalPartCode == toLogicalPartCode).ToList();
            }
            return cellQuery.OrderBy(c=>c.HeightType)
                .ThenBy(c=>c.LineNo)
                .ThenBy(c=>c.DistanceValue)
                .ThenBy(c=>c.LayerNo)
                .ThenBy(c=>c.ColumnNo)
                .ThenBy(c=>c.DepthIndex)
                .ToList();
        }

        /// <summary>
        /// 查询单个移库信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TTransferBinOrder GetTransferBinOrderById(int id)
        {
            return Context.TTransferBinOrders.Find(id);
            //TTransferBinOrderDTO Tdto = new TTransferBinOrderDTO();
            //Tdto = Mapper.Map<TTransferBinOrderDTO>(tran);
            //Tdto.OrderDetailList = Context.TTransferBinOrderDetails.Where(t => t.OrderId == tran.Id).ToList();

        }

        /// <summary>
        /// 查询全部移库单信息
        /// </summary>
        /// <param name="kname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TTransferBinOrder> GetTransferBinOrderList(string AsNoTracking, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var list = Context.TTransferBinOrders.AsQueryable();
                if (!string.IsNullOrEmpty(AsNoTracking))
                {
                    list = list.Where(x => x.OrderSn.Contains(AsNoTracking));
                }
                totalCount = list.Count();
                return list.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 查看移库单的详细信息
        /// </summary>
        /// <param name="Id">移库单id</param>
        /// <returns></returns>
        public TTransferBinOrderDTO SelectTransferBinOrder(int Id)
        {
            var Trans = Context.TTransferBinOrders.FirstOrDefault(t => t.Id == Id);
            if (Trans != null)
            {
                TTransferBinOrderDTO dto = new TTransferBinOrderDTO();
                dto = Mapper.Map<TTransferBinOrderDTO>(Trans);
                dto.OrderDetailList = Context.TTransferBinOrderDetails.Where(t=>t.OrderId==dto.Id).ToList();
                return dto;
            }
            return null;
        }


        /// <summary>
        /// 修改移库单信息
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateTransferBinOrder(TTransferBinOrder t)
        {
            try
            {
                t.ModifyDate = DateTime.Now;
                t.ModifyUserId = t.ModifyUserId;
                t.ModifyUserName = t.ModifyUserName;
                Context.TTransferBinOrders.Update(t);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public bool SubmitTranState(SubmitTranDTO submitTranDTO)
        {
            var user = Context.TUsers.Where(u => u.RealName == submitTranDTO.RealName && u.JobNo == submitTranDTO.JoNO).FirstOrDefault();
            if (user != null)
            {
                var tran = Context.TTransferBinOrders.Where(t => t.Id == submitTranDTO.TranId).FirstOrDefault();
                tran.Status = 2;
                if (UpdateTransferBinOrder(tran))
                {
                    return true;
                }
            }
            return false;
        }
    }
}
